import React from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Card,
  Popconfirm,
  Divider,
  Button,
  Input,
  Drawer,
  Space,
  Table,
  message,
  Modal,
  Tabs,
} from 'antd';
import { connect } from 'umi';
import { PlusOutlined, SyncOutlined } from '@ant-design/icons';
import QuestionEdit from './components/questionEdit';
import QuestionDtlEdit from './components/questionDtlEdit';
import AnswerEdit from './components/answerEdit';
import { CopyQD } from '../../services/crud';
import Evaluation from './components/Evaluation';
import UpdateEva from './components/UpdateEva';
const currControl = 'Edu_QuestionBank';
const { Search } = Input;
const { TabPane } = Tabs;
class ViewPage extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      loading: false,
      loading2: false,
      dataSource: [],
      dataSource2: [],
      dataSource3: [],
      visible: false,
      selectedRowKeys: [],
      pageIndex: 1,
      pageIndex2: 1,
      pageIndex3: 1,
      pageSize: 10,
      totalCount: 0,
      totalCount2: 0,
      totalCount3: 0,
      payload: {},
      record: {},
      recordDtl: {},
      qid: '',
      qdid: '',

      visiblePing: false,
      visibleUpdate: false,
    };
  }
  componentDidMount() {
    this.fetchDatas();
    this.fetchDtlData();
    this.fetchAnsData();
  }
  fetchDatas = () => {
    this.setState({ loading: true });
    const { pageIndex, pageSize, payload } = this.state;
    this.props
      .dispatch({
        type: 'Abp/getList',
        payload: { skipCount: (pageIndex - 1) * pageSize, maxResultCount: pageSize, ...payload },
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        console.log(resp);

        if (resp && resp.result) {
          var dataSource = resp.result.items;
          this.setState({ loading: false, dataSource, totalCount: resp.result.totalCount });
        }
      });
  };
  fetchDtlData = (fid: any = null) => {
    this.setState({ loading2: true });
    const { pageIndex2, pageSize, qid } = this.state;
    var bankId = fid ? fid : qid;
    this.props
      .dispatch({
        type: 'Abp/getList',
        payload: { skipCount: (pageIndex2 - 1) * pageSize, maxResultCount: pageSize, bankId },
        control: 'Edu_QuestionDtl',
      })
      .then(() => {
        var resp = this.props.response;
        if (resp && resp.result) {
          var dataSource2 = resp.result.items;
          this.setState({ loading2: false, dataSource2, totalCount2: resp.result.totalCount });
        }
      });
  };
  fetchAnsData = (fid: any = null) => {
    this.setState({ loading3: true });
    const { pageIndex3, pageSize, qdid } = this.state;
    var questionId = fid ? fid : qdid;
    this.props
      .dispatch({
        type: 'Abp/getList',
        payload: { skipCount: (pageIndex3 - 1) * pageSize, maxResultCount: pageSize, questionId },
        control: 'Edu_Answer',
      })
      .then(() => {
        var resp = this.props.response;
        if (resp && resp.result) {
          var dataSource3 = resp.result.items;
          this.setState({ loading3: false, dataSource3, totalCount3: resp.result.totalCount });
        }
      });
  };
  handleDelete = (id: number, fid: string, control: string = currControl) => {
    this.props
      .dispatch({
        type: 'Abp/delete',
        payload: { id },
        control,
      })
      .then(() => {
        message.success('删除成功！');
        if (control == 'Edu_Answer') this.fetchAnsData(fid);
        else if (control == 'Edu_QuestionDtl') this.fetchDtlData(fid);
        else this.fetchDatas();
      });
  };
  onSelectChange = (record: any) => {
    let _this = this;
    this.setState({ qid: record.id, record }, function () {
      _this.fetchDtlData();
    });
  };
  onSelectChange2 = (record: any) => {
    let _this = this;
    this.setState({ qdid: record.id, record2: record }, function () {
      _this.fetchAnsData();
    });
  };
  onSearch = (value: any) => {
    var payload = this.state.payload;
    payload.keywords = value;
    this.setState({ payload }, () => {
      this.fetchDatas();
    });
  };

  swithEval = (visible: boolean, record = null) => {
    this.setState({ visiblePing: visible, record });
  };
  swithUpdate = (visible: boolean, record = null) => {
    console.log(record);

    this.setState({ visibleUpdate: visible, record });
  };
  openModal = (record: any, layout: string) => {
    this.setState({ visible: true, disabled: true, record, layout });
  };
  swithDrawer = (visible: boolean, record = null) => {
    this.setState({ visible, record });
  };
  swithDrawer2 = (visible: boolean, qid: string, record = null) => {
    this.setState({ visible2: visible, qid, recordDtl: record });
  };
  swithDrawer3 = (visible: boolean, qdid: string, record = null) => {
    this.setState({ visible3: visible, qdid, recordAns: record });
  };
  copyRecd = async (id: any, ctype: number = 0, toId?: any) => {
    if (ctype === 0) {
      await CopyQD({ id }, currControl).then((resp: any) => {
        message.info('复制题库成功！');
        this.fetchDatas();
      });
    } else if (ctype === 1) {
      if (!toId) {
        message.error('请选择复制对象！');
        return;
      }
      await CopyQD({ id, toId }, 'Edu_QuestionDtl').then((resp: any) => {
        message.info('复制题目成功！');
        this.fetchDtlData();
      });
    } else if (ctype === 2) {
      if (!toId) {
        message.error('请选择复制对象！');
        return;
      }
      await CopyQD({ id, toId }, 'Edu_Answer').then((resp: any) => {
        message.info('复制答案成功！');
        this.fetchAnsData();
      });
    }
  };
  render() {
    const {
      loading,
      loading2,
      loading3,
      dataSource,
      dataSource2,
      dataSource3,
      totalCount,
      totalCount2,
      totalCount3,
      pageSize,
      qid,
      qdid,
    } = this.state;
    const columns = [
      {
        title: '序号',
        dataIndex: 'orderId',
      },
      {
        title: '题库编号',
        dataIndex: 'bankNum',
      },
      {
        title: '题库名称',
        dataIndex: 'title',
      },
      {
        title: '分类',
        dataIndex: 'bType',
      },
      {
        title: '适龄',
        render: (record: any) => (
          <span>
            {record.age} ~ {record.ageMax} 月
          </span>
        ),
      },
      {
        title: '操作',
        render: (record: any) =>
          dataSource.length >= 1 ? (
            <span>
              <Popconfirm
                title="确定删除?"
                onConfirm={() => this.handleDelete(record.id, record.id)}
              >
                <a>删除</a>
              </Popconfirm>
              <Divider type="vertical" />
              <a onClick={() => this.swithDrawer(true, record)}>编辑</a>
              <Divider type="vertical" />
              <a onClick={() => this.swithDrawer2(true, record.id)}>添加题目</a>
              <Divider type="vertical" />
              <a onClick={() => this.copyRecd(record.id)}>复制</a>
              <Divider type="vertical" />
              <a onClick={() => this.copyRecd(record.id, 1, qid)}>复制题目</a>
              <Divider type="vertical" />
              <a onClick={() => this.swithEval(true, record)}>创建评测</a>
              <Divider type="vertical" />
              <a onClick={() => this.swithUpdate(true, record.bankNum)}>修改评测</a>
            </span>
          ) : null,
      },
    ];
    const columns2 = [
      {
        title: '序号',
        dataIndex: 'orderId',
      },
      {
        title: '题目编号',
        dataIndex: 'questionNum',
      },
      {
        title: '题目名称',
        dataIndex: 'title',
      },
      {
        title: '类型',
        dataIndex: 'qType',
      },
      {
        title: '操作',
        render: (record: any) =>
          dataSource.length >= 1 ? (
            <span>
              <Popconfirm
                title="确定删除?"
                onConfirm={() =>
                  this.handleDelete(record.id, record.questionBankId, 'Edu_QuestionDtl')
                }
              >
                <a>删除</a>
              </Popconfirm>
              <Divider type="vertical" />
              <a onClick={() => this.swithDrawer2(true, record.questionBankId, record)}>编辑</a>
              <Divider type="vertical" />
              <a onClick={() => this.swithDrawer3(true, record.id)}>添加答案</a>
              <Divider type="vertical" />
              <a onClick={() => this.copyRecd(record.id, 2, qdid)}>复制答案</a>
            </span>
          ) : null,
      },
    ];
    const columns3 = [
      {
        title: '序号',
        dataIndex: 'orderId',
      },
      {
        title: '答案编号',
        dataIndex: 'answerNum',
      },
      {
        title: '答案内容',
        dataIndex: 'ansContent',
      },
      {
        title: '得分',
        dataIndex: 'points',
      },
      {
        title: '操作',
        render: (record: any) =>
          dataSource.length >= 1 ? (
            <span>
              <Popconfirm
                title="确定删除?"
                onConfirm={() => this.handleDelete(record.id, record.questionId, 'Edu_Answer')}
              >
                <a>删除</a>
              </Popconfirm>
              <Divider type="vertical" />
              <a onClick={() => this.swithDrawer3(true, record.questionId, record)}>编辑</a>
            </span>
          ) : null,
      },
    ];
    return (
      <PageHeaderWrapper title={false}>
        <Tabs defaultActiveKey="1">
          <TabPane tab="题库" key="1">
            <Card>
              <Space>
                <Button
                  type="primary"
                  onClick={this.fetchDatas}
                  loading={loading}
                  icon={<SyncOutlined />}
                >
                  刷新
                </Button>
                <Button
                  type="primary"
                  icon={<PlusOutlined />}
                  onClick={() => this.swithDrawer(true)}
                >
                  新增
                </Button>
                <Search
                  style={{ width: 240 }}
                  placeholder="输入关键词搜索"
                  allowClear
                  onSearch={(value) => this.onSearch(value)}
                />
              </Space>
            </Card>
            <Card>
              <Table
                size="small"
                rowKey="id"
                loading={loading}
                rowSelection={{
                  type: 'radio',
                  onSelect: this.onSelectChange,
                }}
                columns={columns}
                dataSource={dataSource}
                pagination={{
                  onChange: (page) => {
                    this.setState({ pageIndex: page }, () => {
                      this.fetchDatas();
                    });
                  },
                  pageSize,
                  total: totalCount,
                }}
              />
            </Card>
          </TabPane>
          <TabPane tab="题目" key="2">
            <Card>
              <Table
                size="small"
                rowKey="id"
                loading={loading2}
                columns={columns2}
                dataSource={dataSource2}
                pagination={{
                  onChange: (page) => {
                    this.setState({ pageIndex2: page }, () => {
                      this.fetchDtlData();
                    });
                  },
                  pageSize,
                  total: totalCount2,
                }}
                rowSelection={{
                  type: 'radio',
                  onSelect: this.onSelectChange2,
                }}
              />
            </Card>
          </TabPane>
          <TabPane tab="答案" key="3">
            <Card>
              <Table
                size="small"
                rowKey="id"
                loading={loading3}
                columns={columns3}
                dataSource={dataSource3}
                pagination={{
                  onChange: (page) => {
                    this.setState({ pageIndex3: page }, () => {
                      this.fetchAnsData();
                    });
                  },
                  pageSize,
                  total: totalCount3,
                }}
              />
            </Card>
          </TabPane>
        </Tabs>

        <Drawer
          width={800}
          placement="right"
          closable={false}
          onClose={() => this.swithDrawer(false)}
          visible={this.state.visible}
          destroyOnClose={true}
        >
          <QuestionEdit ParentData={this.state.record} fetchDatas={this.fetchDatas} />
        </Drawer>
        <Drawer
          width={800}
          placement="right"
          closable={false}
          onClose={() => this.swithDrawer2(false, '')}
          visible={this.state.visible2}
          destroyOnClose={true}
        >
          <QuestionDtlEdit
            ParentData={this.state.recordDtl}
            QId={this.state.qid}
            fetchDatas={this.fetchDtlData}
          />
        </Drawer>
        <Drawer
          width={800}
          placement="right"
          closable={false}
          onClose={() => this.swithDrawer3(false, '')}
          visible={this.state.visible3}
          destroyOnClose={true}
        >
          <AnswerEdit
            ParentData={this.state.recordAns}
            QDId={this.state.qdid}
            fetchDatas={this.fetchAnsData}
          />
        </Drawer>
        <Modal
          title="创建评测标准"
          visible={this.state.visiblePing}
          destroyOnClose={true}
          onCancel={() => this.setState({ visiblePing: false })}
          width={750}
          footer={false}
        >
          <Evaluation
            params={this.state.record}
            fetchDatas={this.fetchDatas}
            visible={this.state.visiblePing}
          />
        </Modal>
        <Modal
          title="修改评测标准"
          visible={this.state.visibleUpdate}
          destroyOnClose={true}
          onCancel={() => this.setState({ visibleUpdate: false })}
          width={1000}
          footer={false}
        >
          <UpdateEva params={this.state.record} fetchDatas={this.fetchDatas} />
        </Modal>
      </PageHeaderWrapper>
    );
  }
}
export default connect(({ Abp }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
}))(ViewPage);
